﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Data;
using System.Text;
using System.Net;
using System.Diagnostics;
using CineProwl.Domain;

namespace CineProwl.Domain.Workers 
{
    public static class FileSystemService
    {
        public static void SaveImageFromWeb(string url, string filepath)
        {
            WebClient webClient = new WebClient();
            webClient.DownloadFile(url, filepath);
        }

        public static void RenameFolder(string oldName, string newName)
        {
            Directory.Move(oldName, newName);
        }

        public static MovieFile GetMovieFileFromFile(string path)
        {
            FileInfo fileInfo = new FileInfo(path);
            if (fileInfo == null)
            {
                throw new FileNotFoundException(path);
            }

            long size = fileInfo.Length / 1000000; //For MB's
            //TODO: Replace with constants
            string quality = "DVD";

            if (size > 4000)
            {
                quality = "1080p";
            }
            else if (size > 1500)
            {
                quality = "720p";
            }
            
            string parentFolder = fileInfo.DirectoryName.Substring(fileInfo.DirectoryName.LastIndexOf("\\") + 1);

            MovieFile movieFile = new MovieFile() {
                Extension = fileInfo.Extension,
                Path = path,
                Size = size,
                Quality = quality,
                ParentFolder = parentFolder
            };

            return movieFile;
        }

        public static string FindMovieFile(string folder)
        {
            //TODO: Move these to config
            List<string> videoExtensions = new List<string>() { "mkv", "avi", "mp4", "m2ts", "m4v", "wmv" };
            var filenames = Directory.EnumerateFiles(folder);
            var filename = (from f in filenames
                            where videoExtensions.Any(e => e == GetExtension(f))
                            && !f.ToLower().Contains("sample")
                            select f).FirstOrDefault();

            return filename;
        }

        public static void PlayMovie(string moviePath)
        {
            string exePath = AppDomain.CurrentDomain.BaseDirectory;
            string rootPath = exePath.Substring(0, exePath.IndexOf("\\CineProwl"));
            string vlcPath = rootPath + "\\CineProwl\\VLCPortable\\VLCPortable.exe";

            Process p = new Process();
            p.StartInfo = new ProcessStartInfo(vlcPath);
            p.StartInfo.Arguments = "-f " + "\"" + moviePath + "\"";
            p.Start();
        }

        private static string GetExtension(string filename)
        {
            return filename.Substring(filename.LastIndexOf(".") + 1).ToLower();
        }
    }
}
